package com.weiquan.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.weiquan.common.Result;
import com.weiquan.dto.CommentRequest;
import com.weiquan.dto.PostPublishRequest;
import com.weiquan.service.CommunityService;
import com.weiquan.utils.JwtUtils;
import com.weiquan.vo.CommentVO;
import com.weiquan.vo.PostVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

/**
 * 社区控制器
 */
@Slf4j
@RestController
@RequestMapping("/community")
@Tag(name = "社区模块", description = "社区帖子和评论相关接口")
public class CommunityController {

    @Autowired
    private CommunityService communityService;

    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 发布帖子
     */
    @PostMapping("/posts")
    @Operation(summary = "发布帖子", description = "用户发布新的社区帖子")
    public Result<Long> publishPost(@Valid @RequestBody PostPublishRequest request, 
                                   HttpServletRequest httpRequest) {
        Long userId = getCurrentUserId(httpRequest);
        Long postId = communityService.publishPost(request, userId);
        return Result.success(postId);
    }

    /**
     * 获取帖子列表
     */
    @GetMapping("/posts")
    @Operation(summary = "获取帖子列表", description = "分页获取社区帖子列表")
    public Result<IPage<PostVO>> getPostList(
            @Parameter(description = "页码") @RequestParam(value = "current", defaultValue = "1") Integer current,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") Integer size,
            @Parameter(description = "分类ID") @RequestParam(required = false) Integer categoryId,
            @Parameter(description = "状态") @RequestParam(required = false) Integer status,
            @Parameter(description = "排序方式") @RequestParam(required = false) String sortBy,
            @Parameter(description = "关键词") @RequestParam(required = false) String keyword,
            HttpServletRequest httpRequest) {
        
        Long userId = getCurrentUserIdOrNull(httpRequest);
        IPage<PostVO> result = communityService.getPostList(current, size, categoryId, status, sortBy, keyword, userId);
        return Result.success(result);
    }

    /**
     * 获取帖子详情
     */
    @GetMapping("/posts/{postId}")
    @Operation(summary = "获取帖子详情", description = "根据帖子ID获取详细信息")
    public Result<PostVO> getPostDetail(@PathVariable Long postId, 
                                       HttpServletRequest httpRequest) {
        Long userId = getCurrentUserIdOrNull(httpRequest);
        PostVO postVO = communityService.getPostDetail(postId, userId);
        return Result.success(postVO);
    }

    /**
     * 获取热门帖子
     */
    @GetMapping("/posts/hot")
    @Operation(summary = "获取热门帖子", description = "获取热门度较高的帖子列表")
    public Result<List<PostVO>> getHotPosts(@RequestParam(defaultValue = "10") Integer limit) {
        List<PostVO> posts = communityService.getHotPosts(limit);
        return Result.success(posts);
    }

    /**
     * 获取精选案例
     */
    @GetMapping("/posts/featured")
    @Operation(summary = "获取精选案例", description = "获取管理员精选的成功案例")
    public Result<List<PostVO>> getFeaturedCases(@RequestParam(defaultValue = "10") Integer limit) {
        List<PostVO> cases = communityService.getFeaturedCases(limit);
        return Result.success(cases);
    }

    /**
     * 点赞/取消点赞帖子
     */
    @PostMapping("/posts/{postId}/like")
    @Operation(summary = "点赞/取消点赞帖子", description = "对帖子进行点赞或取消点赞操作")
    public Result<Boolean> togglePostLike(@PathVariable Long postId, 
                                         HttpServletRequest httpRequest) {
        Long userId = getCurrentUserId(httpRequest);
        Boolean isLiked = communityService.togglePostLike(postId, userId);
        return Result.success(isLiked);
    }

    /**
     * 收藏/取消收藏帖子
     */
    @PostMapping("/posts/{postId}/collect")
    @Operation(summary = "收藏/取消收藏帖子", description = "对帖子进行收藏或取消收藏操作")
    public Result<Boolean> togglePostCollect(@PathVariable Long postId, 
                                            HttpServletRequest httpRequest) {
        Long userId = getCurrentUserId(httpRequest);
        Boolean isCollected = communityService.togglePostCollect(postId, userId);
        return Result.success(isCollected);
    }

    /**
     * 删除帖子
     */
    @DeleteMapping("/posts/{postId}")
    @Operation(summary = "删除帖子", description = "删除用户自己发布的帖子")
    public Result<Boolean> deletePost(@PathVariable Long postId, 
                                     HttpServletRequest httpRequest) {
        Long userId = getCurrentUserId(httpRequest);
        Boolean result = communityService.deletePost(postId, userId);
        return Result.success(result);
    }

    /**
     * 发表评论
     */
    @PostMapping("/comments")
    @Operation(summary = "发表评论", description = "对帖子发表评论或回复")
    public Result<Long> publishComment(@Valid @RequestBody CommentRequest request, 
                                      HttpServletRequest httpRequest) {
        Long userId = getCurrentUserId(httpRequest);
        Long commentId = communityService.publishComment(request, userId);
        return Result.success(commentId);
    }

    /**
     * 获取帖子评论列表
     */
    @GetMapping("/posts/{postId}/comments")
    @Operation(summary = "获取帖子评论列表", description = "获取指定帖子的所有评论")
    public Result<List<CommentVO>> getCommentList(@PathVariable Long postId, 
                                                 HttpServletRequest httpRequest) {
        Long userId = getCurrentUserIdOrNull(httpRequest);
        List<CommentVO> comments = communityService.getCommentList(postId, userId);
        return Result.success(comments);
    }

    /**
     * 点赞/取消点赞评论
     */
    @PostMapping("/comments/{commentId}/like")
    @Operation(summary = "点赞/取消点赞评论", description = "对评论进行点赞或取消点赞操作")
    public Result<Boolean> toggleCommentLike(@PathVariable Long commentId, 
                                            HttpServletRequest httpRequest) {
        Long userId = getCurrentUserId(httpRequest);
        Boolean isLiked = communityService.toggleCommentLike(commentId, userId);
        return Result.success(isLiked);
    }

    /**
     * 删除评论
     */
    @DeleteMapping("/comments/{commentId}")
    @Operation(summary = "删除评论", description = "删除用户自己发表的评论")
    public Result<Boolean> deleteComment(@PathVariable Long commentId, 
                                        HttpServletRequest httpRequest) {
        Long userId = getCurrentUserId(httpRequest);
        Boolean result = communityService.deleteComment(commentId, userId);
        return Result.success(result);
    }

    /**
     * 搜索帖子
     */
    @GetMapping("/search")
    @Operation(summary = "搜索帖子", description = "根据关键词搜索相关帖子")
    public Result<IPage<PostVO>> searchPosts(
            @Parameter(description = "关键词") @RequestParam String keyword,
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer page,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") Integer size,
            HttpServletRequest httpRequest) {
        
        Long userId = getCurrentUserIdOrNull(httpRequest);
        IPage<PostVO> result = communityService.searchPosts(keyword, page, size, userId);
        return Result.success(result);
    }

    /**
     * 获取用户发布的帖子
     */
    @GetMapping("/users/{userId}/posts")
    @Operation(summary = "获取用户发布的帖子", description = "获取指定用户发布的所有帖子")
    public Result<List<PostVO>> getUserPosts(@PathVariable Long userId) {
        List<PostVO> posts = communityService.getUserPosts(userId);
        return Result.success(posts);
    }

    /**
     * 获取用户的评论
     */
    @GetMapping("/users/{userId}/comments")
    @Operation(summary = "获取用户的评论", description = "获取指定用户发表的所有评论")
    public Result<List<CommentVO>> getUserComments(@PathVariable Long userId) {
        List<CommentVO> comments = communityService.getUserComments(userId);
        return Result.success(comments);
    }

    /**
     * 获取分类统计
     */
    @GetMapping("/stats/categories")
    @Operation(summary = "获取分类统计", description = "获取各分类的帖子数量统计")
    public Result<List<Object>> getCategoryStats() {
        List<Object> stats = communityService.getCategoryStats();
        return Result.success(stats);
    }

    /**
     * 获取当前用户ID（必须登录）
     */
    private Long getCurrentUserId(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            return jwtUtils.getUserIdFromToken(token);
        }
        throw new RuntimeException("用户未登录");
    }

    /**
     * 获取当前用户ID（可选登录）
     */
    private Long getCurrentUserIdOrNull(HttpServletRequest request) {
        try {
            return getCurrentUserId(request);
        } catch (Exception e) {
            return null;
        }
    }
}